package com.ytk.ytkclient.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;

import com.ytk.ytkclient.R;
import com.ytk.ytkclient.thread.DeviceSearcherThread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Set;

/**
 * Created by xuchun on 2018/3/8.
 */

public class HomeActivity extends Activity {

    private final String TAG = "HomeActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        findViewById(R.id.send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new DeviceSearcherThread() {
                    @Override
                    public void onSearchStart() {
                        Log.e(TAG,"开始搜索");
                    }

                    @Override
                    public void onSearchFinish(Set<DeviceBean> deviceSet) {
                        for(DeviceBean deviceBean:deviceSet) {
                            Log.e(TAG,"发现目标  ip: " + deviceBean.getIp() + " port：" + deviceBean.getPort());
                        }
                    }
                }.start();
            }
        });
    }


    class MyThread extends Thread {

        public String content;

        public MyThread(String str) {
            content = str;
        }

        @Override
        public void run() {
            //定义消息
            try {
                //连接服务器 并设置连接超时为5秒
                Socket socket = new Socket();
                socket.connect(new InetSocketAddress("172.21.34.19", 9898), 5000);

                //获取输入输出流
                OutputStream ou = socket.getOutputStream();
                //获取输出输出流
                BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                //向服务器发送信息
                ou.write(content.getBytes("utf-8"));
                ou.flush();

                //读取发来服务器信息
                String result = "";
                String buffer = "";
                while ((buffer = bff.readLine()) != null) {
                    result = result + buffer;
                }
                Log.e(TAG,"服务来消息了--> " + result);
                //关闭各种输入输出流
                bff.close();
                ou.close();
                socket.close();
            } catch (SocketTimeoutException e) {
                Log.e(TAG,"SocketTimeoutException--> " + e.getMessage());
            } catch (IOException e) {
                Log.e(TAG,"IOException--> " + e.getMessage());
            }
        }
    }

}
